import Combine

let intPubliser = [Int](1...5).publisher


check("Map") {
    intPubliser.map { $0 * 2 }
}

check("Reduce") { //将数组中的元素按照某种规则进行合并，并得到一个最终的结果
    intPubliser.reduce(0, +)
}

check("Scan") {
    intPubliser.scan(0, +)
}

check("Filter") {
    intPubliser.filter { $0 > 3 }
}

check("CompactMap") {
    ["0", "1", "2" , "three", "4"]
        .publisher
        .compactMap { Int($0) }
}

check("Flat Map 1") { //
    [[1, 2, 3], ["a", "b", "c"]]
        .publisher
        .flatMap {
            $0.publisher
        }
}

check("Flat Map 2") {
    ["A", "B", "C"]
        .publisher
        .flatMap { letter in
            [1, 2, 3]
                .publisher
                .map { "\(letter)\($0)" }
        }
}

check("Remove Duplicates") {
    ["S", "Sw", "Sw", "Sw", "Swi","Swif", "Swift", "Swift", "Swif"]
        .publisher
        .removeDuplicates()
}

//MARK： - 错误处理
enum MyError: Error {
    case myError
}

check("Map Error") {
    Fail<Int, SampleError>(error: .sampleError)
        .mapError { _ in
            MyError.myError
        }
}

check("Throw") {
    ["1", "2", "Swift", "4"]
        .publisher
        .tryMap { s -> Int in
            guard let value = Int(s) else { throw MyError.myError }
            return value
        }
}

check("Replace Error") {
    ["1", "2", "Swift", "4"]
        .publisher
        .tryMap { s -> Int in
            guard let value = Int(s) else { throw MyError.myError }
            return value
        }
        .replaceError(with: -1)
}

check("Catch with Just") {
    ["1", "2", "Swift", "4"]
        .publisher
        .tryMap { s -> Int in
            guard let value = Int(s) else { throw MyError.myError }
            return value
        }
        .catch { _ in
            Just(-1)
        }
}

check("Catch and Continue") {
    ["1", "2", "Swift", "4"]
        .publisher
        .flatMap { s in
            return Just(s)
                .tryMap { s -> Int in
                    guard let value = Int(s) else { throw MyError.myError }
                    return value
                }
                .catch { _ in
                    Just(-1)
                }
        }
}

check("Contains") {
    [1, 2, 3, 4, 5]
        .publisher
        .contains(10)
}

check("Prefix") {
    [1, 2, 3, 4, 5]
        .publisher
        .prefix(2)
}

check("Drop") {
    [1, 2, 3, 4, 5]
        .publisher
        .drop{ $0 < 4 }
}

check("ReplaceNil") {
    [1, 2, 3, 4, 5, nil, 7]
        .publisher
        .replaceNil(with: 6)
}

check("ReplaceEmpty") {
    [].publisher.replaceEmpty(with: "EmptyPlaceHolder")
}

check("Min") {
    //[3, 1, 2]
    ["b", "B", "a"]
        .publisher
        .min()
}

check("Max") {
    //[3, 1, 2]
    ["b", "B", "a"]
        .publisher
        .max()
}

check("AllSatisfy") {
    [1, 2, 3, 4, 5]
        .publisher
        .allSatisfy {
            return $0 > 1 //信号是否全部满足条件
        }
}
